/**
 * OA UI
 * @author:szy
 */


define(function (require, exports, module) {
    require("jquery-ui");
    require("jquery.tinyscrollbar");

    var $body = $("body"), $win = $(window);
    var API = require('./API');

    /**
     * 下拉选择
     * @author:szy
     * @param $wraps
     */
    function selectFun($wrap) {
        var $ipt = $wrap.find(".tit") || $wrap.find(".G_ipt");
        var $ul = $wrap.find(".scrollbarWrap"),$li = $wrap.find("li"), $input = $wrap.find("input[type=hidden]");
        var $GSelectUL = $(".G_select .scrollbarWrap,.G_select .ul"), selectedCall = null;

        var scrollBarWrapUl = $(".G_select .scrollbarWrap ul");


        if ($ul && !$ul[0]) {
            $ul = $wrap.find("ul");
        }

        var otherUlHide = function () {
                $GSelectUL.hide();
                scrollBarWrapUl.show();
            },
            selectAction= function ($li) {
                $li.each(function () {
                    var $this = $(this), _val = $this.attr("data-valve"), _text = $this.text();
                    $this.unbind("click.selected").bind("click.selected", function () {
                        $ipt.text(_text);
                        _val = _val ? _val : _text;
                        $input.val(_val);
                        $ul.hide();
                        $li.removeClass("selected");
                        $this.addClass("selected");
                        selectedCall && selectedCall(_val,_text);
                    })
                })

        };
        selectAction($li);


        $ipt.unbind("click.show").bind("click.show", function () {
            otherUlHide();
            if($li.length<2){
                tooltip("warn","该列表暂无数据")
                return
            }

            $ul.show();
            if ($ul.hasClass("scrollbarWrap")) {
                $ul.tinyscrollbar();
            }
        })
        $(document).unbind("click.stop").bind("click.stop", otherUlHide)
        $wrap.unbind("click.stop").bind("click.stop", function (e) {
            e.stopPropagation();
        })
        $wrap.find(".scrollbar").unbind("click.stop").bind("click.stop", function (e) {
            e.stopPropagation();
        })







        return {
            reset: function () {
                var _data = $ipt.attr("data-default");
                var resetData = _data ? _data : "";
                $ipt.text(resetData);
                $input.val("");
            },
            selected: function (fn) {
                selectedCall = fn;
            },
            /**
             * 更新选择项
             * @param data [{value:"",text:""}]
             */
            updateOption: function (data) {
                var $temp=$("<div></div>");
                for(var i=0;i<data.length;i++){
                    $("<li></li>").attr("data-value",data[i].value).text(data[i].text).appendTo($temp);
                }
                $li=$temp.children();
                var $ull=$wrap.find("ul");
                $ull.find("li[data-valve]").remove().end().append($li);
                selectAction($ull.children());

            }
        }
    }

    /**
     * 自定义多选或单选
     * @author:szy
     */
    function radioSelectedFun($opts) {
        //dom 模板
        //         <div class="radioDoc">
        //        <ul>
        //        <li class="selected" val="1">1</li>
        //        <li val="2">2</li>
        //        <li val="3">3</li>
        //        </ul>
        //        </div>
        var opt = $.extend({
            $selected: "",
            $items: "",
            type: "radio",
            selectedClass: "selected",
            change: function () {

            }
        }, $opts);
        var $selected = opt.$selected;
        var $lis = $selected.find("li") || opt.$items;
        $lis.each(function () {
            var $this = $(this), _value = $this.attr("data-value");
            $this.unbind("click.selected").bind("click.selected", function () {
                if (opt.type == "checkbox") {
                    $this.toggleClass(opt.selectedClass);
                } else if (opt.type == "radio") {
                    $lis.removeClass(opt.selectedClass)
                    $this.addClass(opt.selectedClass);
                }
                opt.change && opt.change.call(this, _value)
            })
        })
        return {
            //返回所选择的值
            values: function () {
                if (opt.type == "checkbox") {
                    return $lis.map(function () {
                        var $this = $(this);
                        if ($this.hasClass(opt.selectedClass)) {
                            return $this.attr("data-value")
                        }
                    }).get().join(",");

                } else if (opt.type == "radio") {
                    var $curr = $lis.filter("." + opt.selectedClass);
                    return $curr && $curr[0] ? $curr.attr("data-value") : "";
                }
            },
            selected: function (values) {
                if (typeof (values) == "string") {
                    values = values.split(",")
                }
                if (values && values[0]) {
                    $lis.removeClass(opt.selectedClass)
                    for (var i = 0; i < values.length; i++) {
                        $lis.filter("[data-value='" + values[i] + "']").addClass(opt.selectedClass)
                    }
                }
            }

        }
    }

    /**
     * 弹窗口
     * @author:szy
     * @param opts
     * @returns {{closeCallback: Function, getDialog: Function}}
     */
    function dialog(opts) {
        var opt = $.extend({
            $tpl: "",//必须,
            $close: "",
            appendCall: function () {
            },
            clickDialogClose: false
        }, opts);
        var $tpl = opt.$tpl.hide(), $close = $tpl.find(".close,.cancel") || opt.$close;

        var closeCallbackFn = null;

        var $dialog = $("<div class='dialogMask'></div>").append($tpl).hide();
        $body.append($dialog);
        opt.appendCall && opt.appendCall();


        $dialog.fadeIn(function () {
            $tpl.fadeIn()
        })

        var tplH = $tpl.outerHeight(), winH = $win.outerHeight();
        if (tplH < winH) {
            var marginTop = Math.floor((winH - tplH) / 2);
            $tpl.css("marginTop", marginTop)
        } else {
            $tpl.css("marginTop", 16)
        }


        var closeFu = function () {
            $tpl.fadeOut(function () {
                $dialog.fadeOut(function () {
                    $dialog.remove();
                    closeCallbackFn && closeCallbackFn();
                })
            })
        }
        if ($close && $close[0]) {
            $close.unbind("click.close").bind("click.close", function () {
                closeFu();
            })
        }
        if (opt.clickDialogClose === true) {
            $dialog.unbind("click.close").bind("click.close", function () {
                closeFu();
            })
            $tpl.unbind("click.close").bind("click.close", function (e) {
                e.stopPropagation();
            })
        }

        return {
            closeCallback: function (fn) {
                closeCallbackFn = fn;
            },
            getDialog: function () {
                return $dialog;
            }

        }
    }

    /**
     *提示框
     * @param type:"success"||"error"||"warn"||"submit"
     * @param info:"要提示的内容"（字符串）
     */
    function tooltip(type, info) {

        $(".tooltip").fadeOut(100, function () {
            $(this).remove()
        })

        var closeCallFn = null, submitCallFn = null;
        var $toolTip = $("<div class='tooltip'></div>").addClass(type).text(info).hide().appendTo($body)
        var width = parseInt($toolTip.css("width"))
        $toolTip.css("marginLeft", (0 - width / 2)).fadeIn();
        var close = function () {
            var _height = $toolTip.outerHeight() + 20;
            //$toolTip.css("top", 0 - _height)
            setTimeout(function () {
                $toolTip.fadeOut(function () {
                    $toolTip.remove()
                });
            }, 300)
        }


        if (type == "submit") {
            var $btns = $("<div class='btns'><button type='button' class='btn cancel'>取消</button><button type='button' class='btn btn-primary submit'>确定</button></div>");
            $btns.appendTo($toolTip);


            $btns.find(".cancel").one("click", function () {
                close();
                closeCallFn && closeCallFn.call(this, "")
                return false
            })
            $btns.find(".submit").one("click", function () {
                close();
                submitCallFn && submitCallFn.call(this, "")
                return false
            })
        } else {
            setTimeout(function () {
                close();
            }, 1000)
        }

        return {
            closeCall: function (fn) {
                closeCallFn = fn
            },
            submitCall: function (fn) {
                submitCallFn = fn;
            }
        }

    }

    /**
     * bootstrap-datetimepicker 封装

     function datetimepicker($obj, params) {
        var setting = $.extend({
            format: 'yyyy-mm-dd hh:ii',
            language: 'zh-CN',
            weekStart: 0,
            todayBtn: 1,
            autoclose: true,
            todayHighlight: 1,
            startView: 2,
            minView: 0,//设置精确到的时间
            forceParse: 0
        }, params)

        var changeDateCall = null, showCall = null;

        var dd = $obj.datetimepicker(setting).unbind("changeDate.dt").bind("changeDate.dt", function (ev) {
            var _value = $obj.find("input").val();
            if (_value) {
                var index = _value.indexOf("-")
                _value = _value.substring(index + 1, _value.length)
                changeDateCall && changeDateCall(ev, _value);
                setTimeout(function () {
                    $obj.datetimepicker("remove")
                }, 1000)
            }
        }).unbind("show.eve").bind("show.eve", function () {
            showCall && showCall();
        })
        return {
            changeDate: function (fn) {
                changeDateCall = fn
            },
            show: function (fn) {
                showCall = fn
            }
        }

    }

     */


    /**
     * jqueryUI datepicker 封装
     */
    function datetimepicker($obj, params) {
        $.datepicker.regional["zh-CN"] = {
            closeText: "关闭",
            prevText: "&#x3c;上月",
            nextText: "下月&#x3e;",
            currentText: "今天",
            monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
            monthNamesShort: ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"],
            dayNames: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
            dayNamesShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
            dayNamesMin: ["日", "一", "二", "三", "四", "五", "六"],
            weekHeader: "周",
            dateFormat: "yy-mm-dd",
            firstDay: 1,
            isRTL: !1,
            showMonthAfterYear: !0,
            yearSuffix: "年",
            beforeShow: function () {
                var $dia = $("#ui-datepicker-div");
                var lock = setInterval(function () {
                    var index = $dia.css("zIndex") * 1
                    if (index > 8) {
                        clearInterval(lock)
                    } else {
                        $dia.css("zIndex", 9);
                    }
                }, 1)
            }
        }
        $.datepicker.setDefaults($.datepicker.regional["zh-CN"]);

        $.extend({}, params);
        $obj.datepicker(params);
    }


    /**
     * ajax 请求封装
     * @param url
     * @param type
     * @param data
     * @param callback
     * @returns {*}
     */
    function ajaxRequest(url, type, data, callback) {
        var $loading = $("<div class='loading'></div>").appendTo($body)
        var ajaxRequestInst = $.ajax({
            url: url,
            type: type,
            data: data,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log("Ajax error:" + errorThrown);
            },
            success: function (json) {
                setTimeout(function () {
                    $loading.remove()
                }, 500)
                if (json.error) {
                    console.log("ajax error:" + json.error);
                    callback && callback("error", json);
                } else {
                    callback && callback("success", json);
                }
            }
        })
        return ajaxRequestInst;
    }

    /**
     * 表单异步提交
     * @param $form [要提交的form表单对象]
     * @param url
     * @param type
     * @param callback
     * @returns {*}
     */
    function ajaxSubmit($form, url, type, callback) {
        var $loading = $("<div class='loading'></div>").appendTo($body)
        var ajaxSubmit = $form.ajaxSubmit({
            url: url,
            type: type,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log("Ajax error:" + errorThrown);
            },
            success: function (json) {
                setTimeout(function () {
                    $loading.remove()
                }, 500)
                if (json.error) {
                    console.log("ajax error:" + json.error);
                    callback && callback("error", json);
                } else {
                    callback && callback.call(this, "success", json);
                }
            },
            delay: function (time, fn) {
                if (typeof(time) == "function") {
                    fn = time;
                    time = 2000;
                }
                setTimeout(function () {
                    fn && fn();
                }, time)
            }
        })
        return ajaxSubmit;
    }

    /**
     * cookie 操作
     * @type {{setCookie: Function, getCookieByName: Function, removeCookie: Function}}
     * @url：https://github.com/szyjava/jquery-cookie
     */
    var cookieFun = {
        setCookie: function (name, value, expires, path) {
            $.cookie(name, value, expires, path)
        },
        getCookieByName: function (name) {
            return $.cookie(name);
        },
        removeCookie: function (name) {
            return $.removeCookie(name); // => true
        }
    }
    return {
        API: API,
        tooltip: tooltip,
        dialog: dialog,
        dropDownSelect: selectFun,
        selectedFun: radioSelectedFun,
        datetimepicker: datetimepicker,
        ajax: ajaxRequest,
        ajaxSubmit: ajaxSubmit,
        cookieFun: cookieFun
    }
})